package com.da.im.handler;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONException;
import com.da.im.ImServer;
import com.da.im.common.ChatMessage;
import com.da.im.common.WsResult;
import com.da.im.common.type.MessageType;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;

/**
 * @author da
 * @time 2023/12/20 上午 10:18
 * 处理消息
 */
public class ChatHandler {
    public static void execute(ChannelHandlerContext ctx, String msg) {
        try {
            ChatMessage chat = JSON.parseObject(msg, ChatMessage.class);
            switch (MessageType.match(chat.getType())) {
                case PRIVATE -> handlerPrivate(ctx, chat);
                case GROUP -> handlerGroup(ctx, chat);
                default -> ctx.channel().writeAndFlush(WsResult.error("不支持的消息类型"));
            }
        } catch (JSONException e) {
            ctx.channel().writeAndFlush(WsResult.error("消息格式错误"));
        } catch (Exception e) {
            ctx.channel().writeAndFlush(WsResult.error(e.getMessage()));
        }
    }

    //处理群聊消息
    private static void handlerGroup(ChannelHandlerContext ctx, ChatMessage chat) {
        //给所有的在线用户发送消息
        ImServer.USERS.values().forEach(channel -> {
            try {
                channel.writeAndFlush(WsResult.success(chat.getName() + "群发", chat.getContent()));
            } catch (Exception e) {
                //群发消息失败
                ctx.channel().writeAndFlush(WsResult.error(e.getMessage()));
            }
        });
    }

    //处理私聊消息
    private static void handlerPrivate(ChannelHandlerContext ctx, ChatMessage chat) {
        //私聊消息需要指定接收人
        if (StrUtil.isNotEmpty(chat.getTarget())) {
            if (chat.getName().equals(chat.getTarget())) {
                ctx.channel().writeAndFlush(WsResult.error("不能自己跟自己发消息"));
                return;
            }
            if (ImServer.USERS.containsKey(chat.getTarget())) {
                Channel channel = ImServer.USERS.get(chat.getTarget());
                //发送私聊消息给对方
                channel.writeAndFlush(WsResult.success(chat.getName(), chat.getContent()));
            } else {
                ctx.channel().writeAndFlush(WsResult.error("用户不在线,无法发送消息"));
            }
        } else {
            ctx.channel().writeAndFlush(WsResult.error("私聊消息需要指定接收人"));
        }
    }


}
